<template>
  <div class="wrapper">
    <el-form ref="editRole" :model="editRoleForm" :rules="rules" label-width="80px">
      <el-form-item label="用户账号">
        <el-input class="w500" v-model="editRoleForm.name" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="可用角色">
        <el-checkbox-group v-model="editRoleForm.role_ids">
          <el-checkbox v-for="item in noPageRoleList" @change="changeRole" :label="item.id" :key="item.id">{{item.name_cn}}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { mapState } from 'vuex'
// import notify from '@/tools/notify'
export default {
  data () {
    return {
      editRoleForm: {
        name: '',
        role_ids: []
      },
      rules: {
        role_ids: [
          {type: 'array', required: true, message: '至少拥有一个角色', trigger: 'blur'}
        ]
      }
    }
  },
  computed: {
    ...mapState({
      noPageRoleList: state => state.role.noPageRoleList,
      userInfo: state => state.user.detail
    }),
    id () {
      return this.$route.params.id
    }
  },
  async mounted () {
    await this.getUserDetail()
    await this.getNoPageRoleList()
    this.getFormDefault()
  },
  methods: {
    // 获取用户信息
    async getUserDetail () {
      let payload = {
        id: this.id
      }
      await this.$store.dispatch('user/userInfo', payload)
    },
    goBack () {
      this.$router.go(-1)
    },
    // 获取所有角色（不分页）
    async getNoPageRoleList () {
      await this.$store.dispatch('role/getNoPageRole')
    },
    // 添加角色或移除角色
    changeRole (checked, event) {
      let payload = {
        id: this.id,
        role_id: event.target._value
      }
      if (checked) { // 添加角色
        this.$store.dispatch('role/addUserOneRole', payload)
      } else { // 移除角色
        this.$store.dispatch('role/removeUserOneRole', payload)
      }
    },
    // 获取表单默认值
    getFormDefault () {
      let roleArray = this.userInfo.role_ids.split(',')
      let tempArray = []
      for (let i = 0; i < roleArray.length; i++) {
        tempArray.push(Number(roleArray[i]))
      }
      this.editRoleForm.role_ids = tempArray
      this.editRoleForm.name = this.userInfo.name
    }
  }
}
</script>
<style scoped lang="scss">
@import "../../../assets/scss/base.scss";
.wrapper{
  .w500 {
    width: 500px;
  }
  .w100 {
    width: 100px;
  }
}
</style>
